//
//  ImageDownloader.m
//  WebImageDemo
//
//  Created by lanou3g on 16/4/22.
//  Copyright © 2016年 浮夸. All rights reserved.
//

#import "ImageDownloader.h"
#import <CommonCrypto/CommonCrypto.h>
@implementation ImageDownloader
///单例
+ (instancetype)shareLoader
{
    static ImageDownloader *loader = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (loader == nil) {
            loader = [ImageDownloader new];
        }
    });
    return loader;
}

- (void)downloadImageWithUrl:(NSURL *)imgUrl result:(void(^)(UIImage *img))block
{
    NSString *urlStr = imgUrl.absoluteString;
    NSString *md5Str = [self md5FromString:urlStr];
    NSString *imgPath = [[self cachsPath]stringByAppendingPathComponent:md5Str];
   // NSLog(@"%@",imgPath);
    //判断文件是否存在
    if ([[NSFileManager defaultManager]fileExistsAtPath:imgPath]) {
        //存在从本地取值
        NSData *data = [self loadImage:imgPath];
        UIImage *img = [[UIImage alloc]initWithData:data];
        block(img);
    }else{
        //不存在下载
        [self loadImageWithUrl:imgUrl block:block];
    }
    
    
    
    
}

//从本地取图片
- (NSData *)loadImage:(NSString *)imgPath
{
    return [NSData dataWithContentsOfFile:imgPath];
}

//从网络下载的方法
- (void)loadImageWithUrl:(NSURL *)imgUrl block:(void(^)(UIImage *img))block
{
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:imgUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            //得到data
            //本地保存一份
            NSString *md5Str = [self md5FromString:imgUrl.absoluteString];
            NSString *imgPath =[[self cachsPath]stringByAppendingPathComponent:md5Str];
            
            [data writeToFile:imgPath atomically:YES];
            //返回block
            UIImage *img = [[UIImage alloc]initWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                block(img);
            });
        }
        
    }];
    [dataTask resume];
}



//文件路径 chches
- (NSString *)cachsPath
{
    return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
}

//把字符串转换为MD5
- (NSString *)md5FromString:(NSString *)str
{
   unsigned char result[16];
    CC_MD5(str.UTF8String, (CC_LONG)strlen(str.UTF8String), result);
    
    NSMutableString *md5Str = [NSMutableString new];
    for (int i =0; i<6; i++) {
        [md5Str appendFormat:@"%02x",result[i]];
    }
    
    return  md5Str;
}


@end
